﻿#include "RegisterCenter_User.h"

#include "User.h"
#include "TcpIOer.h"

RegisterCenter_User::RegisterCenter_User()
{

}

RegisterCenter_User::~RegisterCenter_User()
{

}

bool RegisterCenter_User::isOnline(uint userId)
{
  return userList.contains(userId);
}

bool RegisterCenter_User::isOnline(TcpIOer* tcpIOer)
{
  return tcpIOerToUserIdList.contains(tcpIOer);
}

void RegisterCenter_User::updateLifeTime(uint userId,const int lifeTime_ms)
{
  if(!userIdToTcpIOerList.contains(userId))
    {
      return;
    }
  userIdToTcpIOerList.value(userId)->setCountDown(0==lifeTime_ms?defaultLifeTime:lifeTime_ms);
}

User* RegisterCenter_User::getUserById(uint userId)
{
  return userList.value(userId,Q_NULLPTR);
}

TcpIOer* RegisterCenter_User::getTcpIOerById(uint userId)
{
  return userIdToTcpIOerList.value(userId,Q_NULLPTR);
}

int RegisterCenter_User::getUserIdByTcpIOer(TcpIOer* tcpIOer)
{
  return tcpIOerToUserIdList.value(tcpIOer,0);
}

void RegisterCenter_User::userLogin(User* user,TcpIOer* tcpIOer)
{
  if(userList.contains(user->getUserId()))
    {
      return;
    }
  tcpIOer->setCountDown(defaultLifeTime);
  uint userId=user->getUserId();
  userList.insert(userId,user);
  tcpIOerToUserIdList.insert(tcpIOer,userId);
  userIdToTcpIOerList.insert(userId,tcpIOer);
  connect(tcpIOer,&TcpIOer::signal_lastWish,[=](){userLogout(userId);});
  logSaver->saveLog("RegisterCenter_User,user "+QString::number(userId)+" login");
}

void RegisterCenter_User::userLogout(uint userId)
{
  if(!userList.contains(userId))
    {
      return;
    }
  userList.take(userId)->deleteLater();
  TcpIOer* tcpIOer=userIdToTcpIOerList.take(userId);
  tcpIOerToUserIdList.take(tcpIOer);
  logSaver->saveLog("RegisterCenter_User,user "+QString::number(userId)+" logout");
}

void RegisterCenter_User::userLogout(TcpIOer* tcpIOer)
{
  if(!tcpIOerToUserIdList.contains(tcpIOer))
    {
      return;
    }
  userLogout(tcpIOerToUserIdList.value(tcpIOer));
}
